$(document).ready(function() {
	debug = 1;
	function layout() {
		height = $(window).height();
		bottomHeight = $('.bottom').height();
		bottomWidth = $('.bottom').width();
		$('.container').height(height - bottomHeight);
		$('.valin').width(bottomWidth - 180);
	}
	layout();
	$(window).resize(function(){layout()});

	window.cmdAssist = function(cmd) {
		$('.valin').val(cmd);
	}

	$('#mud').css('position','absolute');
	$('#mud').css('top','0px');
	$('#mud').css('left','0px');

	window.callback = function(json) {
		alert(json);
		//$('.result').proccess(json);
		//$('.container').filter('div').scrollToEnd();
	}

	function sendCmd(cmd) {
		if($('#mud')[0].isConnected())
			$('#mud')[0].sendCmd(cmd);
		else 
			$.ajax({
				url: '/game/cmd',
				data: {cmd:cmd},
				type: 'GET',
				dataType: 'json',
				error: function(req,status,thr){
					if(debug) 
						document.write(req.responseText);
					else
						alert('server error');
				},
				success: function(json) {
					$('.result').proccess(json);
					$('.container').filter('div').scrollToEnd();
				}
			});
	}
	
	$('.valin').bind('keyup',function(event) {
		if(event.keyCode == 13) {
			$('.button').trigger('click');
		}
	});
	$('.button').bind('click',function(){
		sendCmd($('.valin').val());
	});
});

(function($){
	$.fn.scrollToEnd = function() {
		$(this).scrollTop($(this).attr('scrollHeight'));
	}
	$.fn.proccess = function(json) {
		if(json.code == 0) {
			if(json.html)
				$(this).append($("<div class='item'/>").append(json.html));
		} else {
			if(json.html)
				$(this).append($("<div class='item error'/>").append(json.html));
		}
		items = $(this).children('.item');
		max = $(window).data('maxline')||$('.container').height()/12;
		if(items.length > max) {
			for(var i = 0; i < items.length; i++) {
				if(i == parseInt(items.length - max))
					break;
				$(items[i]).remove();
			}
		}
		if(json.script) {
			try {
				eval(json.script);
			} catch(e) {
				if(debug) {
					alert(e);
				}
			}
		}
	}
})(jQuery);
